package com.example.housingRentalSystem.service.Impl;

import com.example.housingRentalSystem.bean.News;
import com.example.housingRentalSystem.mapper.NewsMapper;
import com.example.housingRentalSystem.service.NewsService;
import com.example.housingRentalSystem.utils.PageRequest;
import com.example.housingRentalSystem.utils.PageResponse;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @author 王硕
 * @version jdk21
 * @className NewsServiceImpl
 * @description 新闻服务实现类
 * @date 2025/3/24 16:14
 */
@Service
public class NewsServiceImpl implements NewsService {

    private static final Logger logger = LoggerFactory.getLogger(NewsServiceImpl.class);

    @Autowired
    private NewsMapper newsMapper;

    @Override
    public PageResponse<News> getList(PageRequest pageRequest) {
        pageRequest.validate(); // 校验分页参数
        PageHelper.startPage(pageRequest.getPage(), pageRequest.getSize());
        Page<News> pageResult = newsMapper.selectPage();
        logger.info("Fetched {} news records from database", pageResult.getTotal());
        return PageResponse.build(pageResult);
    }

    @Override
    public Optional<News> getDetail(Integer id) {
        News news = newsMapper.selectById(id);
        if (news == null) {
            logger.warn("新闻不存在或已被删除: ID={}", id);
            return Optional.empty();
        }
        return Optional.of(news);
    }

    @Override
    @Transactional
    public void addNews(News news) {
        if (StringUtils.isBlank(news.getTitle())) {
            throw new IllegalArgumentException("新闻标题不能为空");
        }

        int result = newsMapper.insert(news);
        if (result != 1) {
            logger.error("新闻添加失败: {}", news);
            throw new RuntimeException("新闻添加失败");
        }
    }

    @Override
    @Transactional
    public void updateNews(Integer id, News news) {
        News existNews = newsMapper.selectById(id);


        news.setId(id);
        int result = newsMapper.updateById(news);
        if (result != 1) {
            logger.error("新闻更新失败: ID={}", id);
            throw new RuntimeException("新闻更新失败");
        }
    }

    @Override
    @Transactional
    public void deleteNews(Integer id) {
        int result = newsMapper.deleteById(id);
        if (result != 1) {
            logger.error("新闻删除失败: ID={}", id);
            throw new RuntimeException("新闻删除失败");
        }
    }

    @Override
    public int selectCountNews() {
        int count = newsMapper.selectCountNews();
        return count;
    }
}